import {
    StyleSheet,
    Text,
    View,
    Pressable,
    Image,
    TextInput,
    Dimensions,
} from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import { useRouter, Link, useFocusEffect } from 'expo-router';
import AsyncStorage from '@react-native-async-storage/async-storage'
import axios from 'axios';

export default function Results() {

    const router = useRouter();

    const [searchtext, setsearchtext] = useState('');

    useEffect(() => {
        loadText();
    }, []);

    useEffect(() => {
        if (searchtext) {
            search();
        }
    }, [searchtext]);

    const [searchlist, setsearchlist] = useState([])

    const loadText = async () => {
        try {
            const text = await AsyncStorage.getItem('searchtext');
            if (text) {
                let a = JSON.parse(text)
                setsearchtext(a)
            }
        } catch (error) {
            console.error('Error loading history:', error);
        }
    };

    let search = async () => {
        await axios.get('http://192.168.13.227:3000/lzl/search', {
            params: {
                searchtext: searchtext
            }
        }).then(res => {
            setsearchlist(res.data);
        })
    }

    const replaceCommasWithPipes = (str: String) => {
        return str.replace(/，/g, ' | ');
    };
    const handleLocalstory = async (item: any) => {
        AsyncStorage.setItem('shopInfo', JSON.stringify(item))
        router.push('/DescPage')
    }

    return (
        <View>
            <View style={styles.Input}>
                <Pressable onPress={() => router.push('/home')}>
                    <Image source={require("@/assets/img/左箭头.png")} />
                </Pressable>
                <TextInput
                    style={styles.search}
                    placeholder='精选天然水果'
                    onFocus={() => (
                        router.push('/HomeModel/Search')
                    )}
                />
                <View style={{ backgroundColor: "#99cc33", borderRadius: 100 }}>
                    <Text
                        style={{ paddingHorizontal: 10, paddingVertical: 5, color: "#99cc33" }}

                    >搜索</Text>
                </View>
            </View>
            <View style={[styles.rxItemflex]}>
                {
                    searchlist.map((item: any) => (
                        <Pressable key={item._id} style={styles.rxshopcar} onPress={() => (handleLocalstory(item))}>
                            <Image
                                style={[styles.rxshopimg]}
                                source={{ uri: item.img[0] }}
                            />
                            <View style={{ padding: 10 }}>
                                <Text>{item.name}</Text>
                                <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae", lineHeight: 25 }}>{replaceCommasWithPipes(item.description)}</Text>
                                <Text style={{ fontSize: 18, marginTop: 5, color: 'red', lineHeight: 25 }}>
                                    <Text style={{ fontSize: 12 }}>￥</Text>
                                    {item.price}
                                </Text>
                            </View>
                        </Pressable>
                    ))
                }
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    Input: {
        height: 60,
        backgroundColor: "#99cc33",
        position: "relative",
        display: "flex",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-evenly",
        // alignItems:"flex-start",
        zIndex: 999
    },
    search: {
        width: Dimensions.get('window').width - Dimensions.get('window').width / 2.5,
        borderWidth: 0,
        paddingHorizontal: 15,
        paddingVertical: 5,
        borderRadius: 50,
        backgroundColor: '#fff',
    },
    rxItemflex: {
        width: 310,
        marginTop: 10,
        marginLeft: 'auto',
        marginRight: 'auto',
    },
    rxshopcar: {
        width: 310,
        height: 100,
        marginTop: 5,
        marginBottom: 5,
        display: "flex",
        flexDirection: "row",
        backgroundColor: '#fff',
        borderRadius: 10,
    },
    rxshopimg: {
        width: 100,
        height: 100,
        borderRadius: 10
    },
})